package net.jeeshop.web.action.front;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.jeeshop.web.action.phone.HomeController;
import net.jeeshop.web.util.CheckMobileUtil;

import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 前端首页
 */
@Controller
@RequestMapping("/")
public class IndexAction {
	private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(IndexAction.class);
    @RequestMapping({"/","/index"})
    public String index(HttpServletRequest request,HttpServletResponse response) throws IOException {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
    	boolean isFromMobile=false;
		
		HttpSession session= request.getSession();
    //检查是否已经记录访问方式（移动端或pc端）
		if(null==session.getAttribute("ua")){
			try{
				//获取ua，用来判断是否为移动端访问
				String userAgent = request.getHeader( "USER-AGENT" ).toLowerCase();  
				if(null == userAgent){  
				    userAgent = "";  
				}
				isFromMobile=CheckMobileUtil.check(userAgent);
				//判断是否为移动端访问
				if(isFromMobile){
					LOG.info("移动端访问");
					session.setAttribute("ua","mobile");
				} else {
					LOG.info("pc端访问");
					session.setAttribute("ua","pc");
				}
			}catch(Exception e){}
		}else{
			isFromMobile=session.getAttribute("ua").equals("mobile");
		}
        if(isFromMobile){
        	return "redirect:/phone/home";
        }else{
        	return "index";
        }
		
    }
    
    @RequestMapping("phone")
    public String indexPhone(HttpServletRequest request,HttpServletResponse response) throws IOException {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        return "redirect:/phone/home";
    }
    
    @RequestMapping("phone/order")
    public String indexOrder(HttpServletRequest request,HttpServletResponse response) throws IOException {
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        return "redirect:/phone/order/index";
    }
    
}
